<?php

namespace common\components\aliyun;

use Yii;
use OSS\OssClient;
use OSS\Core\OssException;
use yii\base\InvalidCallException;
use yii\base\InvalidConfigException;

/**
 * AliyunOSS
 *
 * @author emhome
 */
class AliyunOSS extends \yii\base\Component {

    public $accessKeyId = null;
    public $accessKeySecret = null;
    public $endpoint = null;
    public $bucket = null;
    public $host = null;
    //
    private $_client = null;

    /**
     * @inheritdoc
     * @throws InvalidConfigException
     */
    public function init() {
        if ($this->accessKeyId === null) {
            throw new InvalidConfigException('The "accessKeyId" property must be set.');
        } elseif ($this->accessKeySecret === null) {
            throw new InvalidConfigException('The "accessKeySecret" property must be set.');
        } elseif ($this->endpoint === null) {
            throw new InvalidConfigException('The "endpoint" property must be set.');
        } elseif ($this->bucket === null) {
            throw new InvalidConfigException('The "bucket" property must be set.');
        } elseif ($this->host === null) {
            throw new InvalidConfigException('The "host" property must be set.');
        }
        try {
            $this->_client = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        } catch (OssException $e) {
            throw new InvalidCallException($e->getMessage());
        }
    }

    public function getClient() {
        return $this->_client;
    }

    public function putObjectACL($filename, $acl) {
        try {
            return $this->client->putObjectAcl($this->bucket, $filename, $acl);
        } catch (OssException $e) {
            Yii::error($e, __METHOD__);
            return false;
        }
    }

    public function putObject($filename, $content, $options = null) {
        return $this->client->putObject($this->bucket, $filename, $content, $options);
    }

    /**
     * 上传文件
     * @param type $filename
     * @param type $path
     * @param type $acl  读写权限，可选值['private', 'public-read', 'public-read-write']
     * @return type
     */
    public function uploadFile($filename, $path, $acl = 'private') {
        $client = $this->client;
        $client->createObjectDir($this->bucket, dirname($filename));
        $client->uploadFile($this->bucket, $filename, $path);
        try {
            $client->putObjectAcl($this->bucket, $filename, $acl);
            return true;
        } catch (OssException $e) {
            return false;
        }
    }

}
